package com.zxl.always.on.display.ui.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

/**
 * Created by Administrator on 2018/3/6.
 */

public class BackgroundLayout extends RelativeLayout {

    private int mResource = -1;

    private int mAvailableWidth, mAvailableHeight;

    public BackgroundLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setResource(int mResource) {
        this.mResource = mResource;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mAvailableHeight = getMeasuredHeight();
        mAvailableWidth = getMeasuredWidth();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        if (mResource != -1) {
            Drawable drawable = getResources().getDrawable(mResource);
            setBoundAtCenter(drawable, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            drawable.draw(canvas);
        }
        super.dispatchDraw(canvas);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mResource != -1) {
            Drawable drawable = getResources().getDrawable(mResource);
            setBoundAtCenter(drawable, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            drawable.draw(canvas);
        }
        super.onDraw(canvas);
    }

    private void setBoundAtCenter(Drawable drawable, int width, int height) {
        if (drawable != null) {
            int left = (this.mAvailableWidth - width) / 2;
            int top = (this.mAvailableHeight - height) / 2;
            drawable.setBounds(left, top, left + width, top + height);
        }
    }
}
